Skip to main content

Coding 5: Connect to RESTful API Using Axios (READ)

🎯 Objective:

  • Install Axios
  • Create a reusable API service
  • Fetch tasks from the backend
  • Display real data in the table

🛠️ A. Install Axios

npm install axios

📦 B. Create Axios Service Layer

Create a folder for API services:

mkdir -p src/lib && touch src/lib/api.ts

Now define the Axios instance:

// src/lib/api.ts
import axios from "axios"

const API_BASE_URL = "https://your-api-url.com/api" // 🔁 Replace with your actual endpoint

export const api = axios.create({
baseURL: API_BASE_URL,
headers: {
"Content-Type": "application/json",
},
})

📡 C. Create a Task Service

// src/lib/taskService.ts
import { api } from "./api"

export interface Task {
id: string
title: string
description: string
priority: string
isCompleted: boolean
dueDate: string
}


// Fetch all tasks
export async function fetchTasks(): Promise<Task[]> {
const response = await api.get("api/tasks")
return response.data
}

📄 D. Use It in TaskPage.tsx

Update TaskPage to fetch from the backend:

import { useEffect, useState } from "react"
import TaskTable from "@/components/task/TaskTable"
import { fetchTasks, Task } from "@/lib/taskService"

export default function TaskPage() {
const [tasks, setTasks] = useState<Task[]>([])
const [loading, setLoading] = useState(true)

useEffect(() => {
const getTasks = async () => {
try {
const data = await fetchTasks()
setTasks(data)
} catch (err) {
console.error("Failed to fetch tasks:", err)
} finally {
setLoading(false)
}
}

getTasks()
}, [])

return (
<div className="max-w-4xl mx-auto mt-10 space-y-6">
<h1 className="text-3xl font-bold text-center">📋 Task Table</h1>

{loading ? (
<p className="text-center text-gray-500">Loading tasks...</p>
) : (
<TaskTable tasks={tasks} />
)}
</div>
)
}

✅ Output

You now have a real-time task table that pulls live data from your REST API using Axios.


📌 Notes:

  • Replace "https://your-api-url.com/api" with your actual backend URL (from your GitLab project).
  • If your API is hosted locally (e.g., localhost:5000), use a proxy or allow CORS.